package com.compass.mobile.ui.activity.static_page

import LogUtil
import android.annotation.SuppressLint

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.fragment.app.activityViewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import androidx.leanback.widget.OnChildViewHolderSelectedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.compass.mobile.framework.update.manager.DownloadManager
import com.compass.mobile.R
import com.compass.mobile.databinding.ActivityHospitalPageBinding
import com.compass.mobile.framework.base.BaseVBActivity
import com.compass.mobile.framework.constant.KEY_TOKEN
import com.compass.mobile.framework.update.util.ApkUtil
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.Dictionaries
import com.compass.mobile.models.UpdateInfo
import com.compass.mobile.presenters.DictionariesPresenter
import com.compass.mobile.ui.activity.MyOrderActivity
import com.compass.mobile.ui.activity.static_page.fragment.HospitalFragment
import com.compass.mobile.ui.viewModel.MainViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import toJson

/**
 * Description： 医院选择界面--新
 * Date:2024/8/20 9:48
 */
class HospitalPageActivity : BaseVBActivity<ActivityHospitalPageBinding>() {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, MyOrderActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val mainViewModel: MainViewModel by viewModels()
    private var list: MutableList<Dictionaries> = mutableListOf()
    private lateinit var hospitalFragment: HospitalFragment

    override fun initView(savedInstanceState: Bundle?) {
        val token: String? = intent.data?.getQueryParameter("token")
        hospitalFragment = HospitalFragment()
        val bundle = Bundle()
        bundle.putString(KEY_TOKEN, token)
        hospitalFragment.arguments = bundle
        displaySelectedFragment(hospitalFragment)
    }


    override fun initData() {
        list.add(Dictionaries("西安市", "2"))
//        list.add(Dictionaries("宝鸡市", "3"))
//        list.add(Dictionaries("铜川市", "4"))
//        list.add(Dictionaries("渭南市", "5"))
//        list.add(Dictionaries("榆林市", "6"))
//        list.add(Dictionaries("汉中市", "7"))
        initCaseTitle(list)
        mainViewModel.getAppVersion()
        mainViewModel.versionLiveData.observe(this) {
            it?.let { updateInfo ->
                LogUtil.e("update_info===${updateInfo.toJson()}")
                LogUtil.e("update_info===${ApkUtil.getVersionCode(application)}")
                LogUtil.e("update_info===${ApkUtil.getVersionCode(application)}")
                updateTest(updateInfo)
            }

        }
    }


    // 根据需要显示或替换Fragment
    private fun displaySelectedFragment(fragment: Fragment) {
        val fragmentTransaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.fragmentChild, fragment)
        fragmentTransaction.commit()
    }

    @SuppressLint("RestrictedApi")
    fun initCaseTitle(dictionaries: MutableList<Dictionaries>?) {
        mBinding.gridCase.verticalSpacing = dpToPx(10)
        val arrayObjectAdapter = ArrayObjectAdapter(DictionariesPresenter())
        val itemBridgeAdapter = MyBridgeAdapter(
            this,
            arrayObjectAdapter, null
        )
        mBinding.gridCase.setAdapter(itemBridgeAdapter)
        arrayObjectAdapter.addAll(0, dictionaries)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )
        mBinding.gridCase.setOnChildViewHolderSelectedListener(onChildViewHolderSelectedListener)
        lifecycleScope.launch {
            delay(500)
            //延迟获取焦点
            mBinding.gridCase.requestFocus()
        }

    }


    // 保存上一个选中的位置 实现高亮显示效果
    var lastSelectedPosition: Int = -1
    private val onChildViewHolderSelectedListener: OnChildViewHolderSelectedListener = object :
        OnChildViewHolderSelectedListener() {
        override fun onChildViewHolderSelected(
            parent: RecyclerView?,
            childViewHolder: RecyclerView.ViewHolder?,
            position: Int,
            subposition: Int
        ) {
            childViewHolder?.itemView?.setBackgroundResource(R.drawable.case_focus)
            if (lastSelectedPosition != -1) {
                var lastViewHolder = parent?.findViewHolderForAdapterPosition(lastSelectedPosition)
                lastViewHolder?.itemView?.setBackgroundResource(R.drawable.case_title_selector)
            }
            lastSelectedPosition = position
            val item = list?.get(position)
            item?.let {
                hospitalFragment.setSelect(it.value)
            }

        }
    }

    //下载URl 为固定不变的 这里写死
    private var url = "https://yd.xawellcare.com/ZHWZ.apk"
    private var manager: DownloadManager? = null
    private fun updateTest(updateInfo: UpdateInfo) {
        manager = DownloadManager.Builder(this).run {
            apkUrl(updateInfo.url)
//            apkUrl(url)
            apkName("ZHWZ.apk")
            smallIcon(R.mipmap.ic_launcher)
                .jumpInstallPage = false
            forcedUpgrade(true)
            //设置了此参数，那么内部会自动判断是否需要显示更新对话框，否则需要自己判断是否需要更新
            apkVersionCode(updateInfo.versionCode)
            //同时下面三个参数也必须要设置
            apkVersionName(updateInfo.apkVersionName)
            apkSize(updateInfo.apkSize)
            apkDescription(updateInfo.apkDescription)
                .apkMD5("")
            //省略一些非必须参数...
            build()
        }
        manager?.download()
    }
}